/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.user.server.impl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

/**
 * 
 * @author jeremie
 *
 */
@Singleton
public class SessionCookieImpl implements Cookies {

	private static final Logger logger = LoggerFactory.getLogger(SessionCookieImpl.class);
	
	/*
	 * 
	 */
	@Inject
	Provider<HttpServletRequest> request;
	
	/*
	 * 
	 */
	@Inject
	Provider<HttpServletResponse> response;

	/*
	 * 
	 */
	@Inject
	Provider<HttpSession> session;
	
	/*
	 * (non-Javadoc)
	 * @see org.jb.user.server.impl.Cookies#getUserPasswordCookies()
	 */
	@Override
	public String getUserCookie() {
		String value = getUserPasswordCookie();
		if (value == null)
			return null;
				
		int idx = value.indexOf(SEPARATOR);
		if (idx == -1)
			return null;

		return value.substring(0, idx);
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.jb.user.server.impl.Cookies#getPasswordCookie()
	 */
	@Override
	public String getPasswordCookie() {
		String value = getUserPasswordCookie();
		if (value == null)
			return null;
				
		int idx = value.indexOf(SEPARATOR);
		if (idx == -1)
			return null;

		return value.substring(idx + 1 );
	}
	
	/*
	 * 
	 */
	private String getUserPasswordCookie() {
		Cookie[] cookies = request.get().getCookies();
		
		if (cookies == null || cookies.length == 0) {
			logger.debug("No cookies found in request");
			return null;
		}
		
		for( Cookie cookie : cookies ) {
			if ("ID".equals( cookie.getName())) {
				String value = cookie.getValue();
				logger.debug( "Cookie ID found {}", value );
				if (value == null || value.isEmpty())
					return null;
				
				return value;
			}
		}
		
		logger.debug( "No Cookie 'ID' found");
		
		return null;
	}

	/*
	 * (non-Javadoc)
	 * @see org.jb.user.server.impl.Cookies#invalidate()
	 */
	@Override
	public void invalidate() {
		session.get().invalidate();
	}

	/*
	 * (non-Javadoc)
	 * @see org.jb.user.server.impl.Cookies#setUserPasswordCookies(java.lang.String)
	 */
	@Override
	public void setUserPasswordCookies( String user, String password ) {
		Cookie cookie = new Cookie( "ID" , user + SEPARATOR + password );
		cookie.setMaxAge( 7 * 24 * 60 * 60 );
		
		String ctxt = request.get().getContextPath();
		if (!ctxt.startsWith("/"))
			ctxt = "/" + ctxt;
		cookie.setPath( ctxt );
		
		logger.debug("Setting permanent cookie for user {} and path={}", ctxt );

		response.get().addCookie( cookie );
	}
	
	private static final char SEPARATOR = '/';
}
